#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    int sockfd;
    char buffer[2000];
    struct sockaddr_in servaddr, cliaddr;

    // 创建socket
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&servaddr, 0, sizeof(servaddr));
    memset(&cliaddr, 0, sizeof(cliaddr));

    // 填充服务器信息
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(5678);  // 使用与发送端相同的端口

    // 绑定socket
    if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port 5678...\n");

    socklen_t len = sizeof(cliaddr);
    int n;

    while(true) {
        n = recvfrom(sockfd, (char *)buffer, sizeof(buffer), MSG_WAITALL,
                     (struct sockaddr *) &cliaddr, &len);
        buffer[n] = '\0';
        printf("Received %d bytes from %s:%d\n", n,
               inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
        printf("Data: %s\n", buffer);
    }

    close(sockfd);
    return 0;
}